import { useState, useCallback } from "react";
import {
  TextField,
  Thumbnail,
  Button,
  Icon,
  Tooltip,
  Popover,
  Listbox,
  Link,
  AutoSelection,
  Scrollable,
  EmptySearchResult,
  Text,
  DropZone,
  LegacyStack,
  OptionList,
  LegacyCard,
} from "@shopify/polaris";
import {
  AttachmentMajor,
  HashtagMajor,
  SmileyHappyMajor,
  MentionMajor,
  SearchMinor,
  NoteMinor,
  CustomersMajor,
  OrdersMinor,
  ProductsMinor,
  ChecklistAlternateMajor,
  ChevronRightMinor,
  MobileCancelMajor,
} from "@shopify/polaris-icons";

const actionValue = "__ACTION__";

const segments = [
  {
    label: "#4711125653341",
    id: "gid://shopify/CustomerSegment/1",
    value: "0",
    img: "https://burst.shopifycdn.com/photos/black-leather-choker-necklace_373x@2x.jpg",
  },
];

const interval = 25;

interface Segments {
  label: string;
  id: string;
  value: string;
  img: string;
}

interface Props {
  value: string;
  setValue: (value: string) => void;
  segments?: Segments[];
  close: (value: boolean) => void;
}
const App = ({ value, setValue, close }: Props) => {
  const [showFooterAction, setShowFooterAction] = useState(false);
  const [query, setQuery] = useState<string>("");
  const [lazyLoading, setLazyLoading] = useState(false);
  const [willLoadMoreResults, setWillLoadMoreResults] = useState(true);
  const [visibleOptionIndex, setVisibleOptionIndex] = useState(6);
  const [activeOptionId, setActiveOptionId] = useState(segments[0].id);
  const [selectedSegmentIndex, setSelectedSegmentIndex] = useState(0);
  const [filteredSegments, setFilteredSegments] = useState<
    (typeof segments)[number][]
  >([]);

  const handleClickShowAll = () => {
    setShowFooterAction(false);
    setVisibleOptionIndex(segments.length);
  };

  const handleFilterSegments = (query: any) => {
    const nextFilteredSegments = segments.filter((segment) => {
      return segment.label
        .toLocaleLowerCase()
        .includes(query.toLocaleLowerCase().trim());
    });

    setFilteredSegments(nextFilteredSegments);
  };

  const handleQueryChange = (query: any) => {
    setQuery(query);

    if (query.length >= 2) handleFilterSegments(query);
  };

  const handleQueryClear = () => {
    handleQueryChange("");
  };

  const handleSegmentSelect = (segmentIndex: string) => {
    if (segmentIndex === actionValue) {
      return handleClickShowAll();
    }

    setSelectedSegmentIndex(Number(segmentIndex));

    setValue(value + segments[Number(segmentIndex)].label + " ");
    close(false);
  };

  const handleActiveOptionChange = (_: string, domId: string) => {
    setActiveOptionId(domId);
  };

  const handleLazyLoadSegments = () => {
    if (willLoadMoreResults && !showFooterAction) {
      setLazyLoading(true);

      const options = query ? filteredSegments : segments;

      setTimeout(() => {
        const remainingOptionCount = options.length - visibleOptionIndex;
        const nextVisibleOptionIndex =
          remainingOptionCount >= interval
            ? visibleOptionIndex + interval
            : visibleOptionIndex + remainingOptionCount;

        setLazyLoading(false);
        setVisibleOptionIndex(nextVisibleOptionIndex);

        if (remainingOptionCount <= interval) {
          setWillLoadMoreResults(false);
        }
      }, 1000);
    }
  };

  const listboxId = "SearchableListbox";

  const textFieldMarkup = (
    <div style={{ padding: "12px" }}>
      <TextField
        // focused={showFooterAction}
        clearButton
        labelHidden
        label=""
        placeholder="搜索"
        autoComplete="off"
        value={query}
        prefix={<Icon source={SearchMinor} />}
        ariaActiveDescendant={activeOptionId}
        ariaControls={listboxId}
        onChange={handleQueryChange}
        onClearButtonClick={handleQueryClear}
      />
    </div>
  );

  const segmentOptions = query ? filteredSegments : segments;

  const segmentList =
    segmentOptions.length > 0
      ? segmentOptions
          .slice(0, visibleOptionIndex)
          .map(({ label, id, value, img }) => {
            const selected = segments[selectedSegmentIndex].value === value;
            return (
              <Listbox.Option key={id} value={value} selected={selected}>
                <Listbox.TextOption selected={selected}>
                  {label}
                </Listbox.TextOption>
              </Listbox.Option>
            );
          })
      : null;

  const listboxMarkup = (
    <Listbox
      enableKeyboardControl
      autoSelection={AutoSelection.FirstSelected}
      accessibilityLabel="Search for and select a customer segment"
      customListId={listboxId}
      onSelect={handleSegmentSelect}
      onActiveOptionChange={handleActiveOptionChange}
    >
      {segmentList}
      {/* {showAllMarkup} */}
      {/* {noResultsMarkup} */}
      {/* {lazyLoadingMarkup} */}
    </Listbox>
  );

  return (
    <div
      style={{
        alignItems: "stretch",
        borderTop: "1px solid #DFE3E8",
        display: "flex",
        flexDirection: "column",
        justifyContent: "stretch",
        position: "relative",
        width: "100%",
        height: "100%",
        overflow: "hidden",
      }}
    >
      {textFieldMarkup}

      <Scrollable
        shadow
        style={{
          position: "relative",
          // height: "292px",
          padding: "var(--p-space-2) 0",
          borderBottomLeftRadius: "var(--p-border-radius-2)",
          borderBottomRightRadius: "var(--p-border-radius-2)",
        }}
        onScrolledToBottom={handleLazyLoadSegments}
      >
        {listboxMarkup}
      </Scrollable>
    </div>
  );
};

export default App;
